import os

from alipay import AliPay
from django.conf import settings
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from orders.models import OrderInfo
from payment.models import Payment


class PaymentView(APIView):
    '''构建支付跳转链接'''
    def get(self, request, order_id):
        # 判断ordre_id有效性
        try:
            order = OrderInfo.objects.get(user=request.user, order_id=order_id, pay_method=2, status=1)
        except:
            return Response({'errorｓ': '无效的订单'}, status=405)

        # 支付对象初始化生成
        # 构造支付宝支付链接地址
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        # 生成连接中的查询字符串参数
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # 订单编号
            total_amount=str(order.total_amount),  # 订单总价
            subject="美多商城%s" % order_id,  # 标题
            return_url="http://www.meiduo.site:8080/pay_success.html",  # 跳转回美多的连接
        )
        # 生成跳转链接
        alipay_url = settings.ALIPAY_URL + order_string

        return Response({'alipay_url': alipay_url})


class PaymentSaveView(APIView):

    def put(self, request):
        # 获取前端信息
        data = request.query_params.dict()
        # sign 不能参与签名验证
        signature = data.pop("sign")

        # 支付对象初始化生成
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )
        # 验证数据是否是支付宝发过来的
        # verify
        success = alipay.verify(data, signature)
        if success:
            # 获取order_id
            order_id = data['out_trade_no']
            # 获取支付宝交易流水号
            trade_id = data['trade_no']
            # 绑定操作
            Payment.objects.create(order_id=order_id, trade_id=trade_id)
            # 修改订单状态
            OrderInfo.objects.filter(order_id=order_id).update(status=2)
            return Response({'trade_id': trade_id})
        else:
            return Response({'errors': '无效的支付宝信息'}, status=405)